<?php
class TicketsController extends Controller
{
	public function init()
	{
		parent::init();
		if (Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
		}
	}
	
	public function actionIndex()
	{
		$this->redirect(Yii::app()->createUrl('tickets/list'));
		exit;
	}

	public function actionList()
	{		
		$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
		$intPage = Yii::app()->request->getParam('page', 1);
		
		$arrFilters = array(
			'keyword' => Yii::app()->request->getParam('keyword', null),
			'dept' => Yii::app()->request->getParam('dept', null),
			'deptName' => Yii::app()->request->getParam('deptName', null),
			'subject' => Yii::app()->request->getParam('subject', null),
			'status' => Yii::app()->request->getParam('status', null),
			'urgency' => Yii::app()->request->getParam('urgency', null),
			'dfrom' => Yii::app()->request->getParam('dfrom', null),
			'dto' => Yii::app()->request->getParam('dto', null),
			'filter' => Yii::app()->request->getParam('filter', null),
		);
		foreach($arrFilters as &$R){
			if($R == '') $R = null;	
		}
		$postCateId = $arrFilters['dept'];
		if($arrFilters['subject'] != '') $postCateId = $arrFilters['subject'];
		
		/*determine user role*/
		$role = Yii::app()->user->getState('roles');
		$ticketCreator = Yii::app()->user->id;
		foreach($role as $id => $roleName){
			if($id == 1 || $id == 2) $ticketCreator = null;
		}
		
		/*query post*/
		$arrTickets = Posts::getInstance()->getList(array(
			'keyword' => '%'.$arrFilters['keyword'].'%',
			'taxonomy_id' => 4,
			'post_status' => $arrFilters['status'],	
			'post_parent' => null,
			'post_creator' => $ticketCreator,
			'category_id' => $postCateId,
			'post_created_date_from' => (!empty($arrFilters['dfrom']))?DateTime::createFromFormat('d/m/Y', $arrFilters['dfrom'])->format('Y-m-d'):null,
			'post_created_date_to' => (!empty($arrFilters['dto']))?DateTime::createFromFormat('d/m/Y', $arrFilters['dto'])->format('Y-m-d'):null,
			'page' => $intPage,
			'limit' => $intRowsPerPage,
		)); //o($arrTickets);
		$intTotalRows = isset($arrTickets[0]['total_rows'])?$arrTickets[0]['total_rows']:0;
		foreach($arrTickets as $key=>$R){
			$arrTickets[$key]['post_category'] = Posts::getInstance()->getCategories($R['post_id']);
		}
		
		//paging
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		/*load list of depts*/
		$arrDepts = HelpDesk::getInstance()->getDepts(true); //o($arrDepts);
		
		/*load current dept*/
		$dept = array();
		if(!empty($arrFilters['dept'])){
			foreach($arrDepts as $key=>$R){
				if($R['category_id'] == $arrFilters['dept']){
					$dept = $arrDepts[$key];
				}
			}
			if(empty($dept)){
				$this->redirect('/error.html');	
			}	
		}
		
		//render layout
		$this->render('list', array(
			'arrFilters' => $arrFilters,
			'arrTickets' => $arrTickets,
			'objPages' => $objPages,
			'arrDepts' => $arrDepts,
			'dept' => $dept
		));	

		//set history
		$_SESSION['history'] = Utils::getCurrentUrl();
	}

	public function actionCreate()
	{		
		//post ticket
		if(Yii::app()->request->isPostRequest)
		{
			$args = array(
				'taxonomy_id' => 4,
				'post_title' => Yii::app()->request->getParam('title', null),
				'post_body' => Yii::app()->request->getParam('body', null),
				'post_creator_id' => Yii::app()->user->id,
				'post_created_date' => date('Y-m-d H:i:s'),
				'post_published_date' => date('Y-m-d H:i:s'),
				'post_status' => 1
			);	
			
			try{
				//create ticket
				$intArticleId = Posts::getInstance()->insert($args);
				
				if($intArticleId > 0){
					//udpate category (dept & subject)
					$arrCategoryIds =   Yii::app()->request->getParam('dept', null);
					if(!empty($arrCategoryIds)){
						Posts::getInstance()->updateCategory($intArticleId, $arrCategoryIds);
					}
					
					//update custom fields
					$arrFields = Yii::app()->request->getParam('fields', null);
					if(is_array($arrFields)){
						foreach($arrFields as $intFieldId => $strFieldValue){
							$strFieldValue = trim($strFieldValue);
							if(!empty($intFieldId)){
								Posts::getInstance()->updateField($intArticleId, $intFieldId, $strFieldValue);
							}
						} 					
					}
					
					//upload attachments
					if($_FILES['attach']['error'] == UPLOAD_ERR_OK){						
						$path = $this->uploadAttachment($_FILES['attach']);
						$attachField = Posts::getInstance()->getFieldByName('helpdesk-attachment');
						Posts::getInstance()->updateField($intArticleId, $attachField['field_id'], $path);
					}
				}
				
				/*write log*/
				Logs::getInstance()->insert(array(
					'user_id' => Yii::app()->user->id,
					'user_ip' => Utils::getIp(),
					'user_agent' => $_SERVER['HTTP_USER_AGENT'],
					'log_action' => 'HELPDESK_CREATE_TICKET',
					'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b>'.' tạo ticket '.'<a href="/tickets/'.$intArticleId.'.html">'.$args['post_title'].'</a>'
				));
				
				//send mail 
				$mailInfo = array(
					'creator_id' => Yii::app()->user->id,
					'ticket_creator_id' => Yii::app()->user->id,
					'ticket_id' => $intArticleId,
					'ticket_title' => $args['post_title'],
					'ticket_body' => $args['post_body'],
					'category_id' => isset($arrCategoryIds)?$arrCategoryIds:array()
				);
				HelpDesk::getInstance()->sendMail('ticket', $mailInfo);												
				
				//done
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
				if(!isset($_SESSION['history'])) $_SESSION['history'] = '/tickets.html';
				$this->redirect($_SESSION['history']);
				//$this->refresh();
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}
		/*load list of depts*/
		$arrDepts = HelpDesk::getInstance()->getDepts(true); //o($arrDepts);
		
		/*load current dept*/
		$dept_id = Yii::app()->request->getParam('dept_id', null);
		$dept = array();
		if(!empty($dept_id)){
			foreach($arrDepts as $key=>$R){
				if($R['category_id'] == $dept_id){
					$dept = $arrDepts[$key];
				}
			}
			if(empty($dept)){
				$this->redirect('/error.html');	
			}		
		}
		
		/*load user*/
		$user = Users::getInstance()->get(Yii::app()->user->id);
		
		$this->render('create', array(
			'arrDepts' => $arrDepts,
			'user' => $user,
			'dept_id' => $dept_id,
			'dept' => $dept
		));	
	}
	
	public function actionDetail(){
		//get params
		$intPostId =  Yii::app()->request->getParam('postId', null);
		
		//load detail
		$post = Posts::getInstance()->get($intPostId);
		
		//check validity
		if(empty($post) || $post['taxonomy_id'] != '4'){
			$this->redirect('/error.html');	
		}
		
		$post['post_creator_profile'] = Users::getInstance()->getProfile($post['post_creator_id']);
		
		//load replies
		$arrReplies = Posts::getInstance()->getList(array(
			'taxonomy_id' => 4,
			'post_status' => 1,	
			'post_parent' => $intPostId,			
			'page' => 1,			
			'limit' => 100,
			'order_by' => 'post_created_date',
			'order' => 'ASC'
		));
		foreach($arrReplies as $key=>$R){
			if(!empty($R['post_creator_id'])){
				$arrReplies[$key]['post_creator_profile'] = Users::getInstance()->getProfile($R['post_creator_id']);
			}
		}
		
		/*load author*/
		$user = array();
		if(!empty($post['post_creator_id'])){
			$user = Users::getInstance()->get($post['post_creator_id']);
		}
		
		/*load dept.*/
		$arrDepts = HelpDesk::getInstance()->getDepts(true);
		
		//render layout
		$this->render('detail', array(
			'post' => $post,
			'user' => $user,
			'arrReplies' => $arrReplies,
			'arrDepts' => $arrDepts
		));
	}
	
	public function actionReply(){
		//get params
		$intParentPostId =  Yii::app()->request->getParam('parentPostId', null);
		if(Yii::app()->request->isPostRequest)
		{
			$args = array(
				'taxonomy_id' => 4,
				'post_title' => '',
				'post_body' => Yii::app()->request->getParam('body', null),			
				'post_creator_id' => Yii::app()->user->id,
				'post_created_date' => date('Y-m-d H:i:s'),
				'post_status' => 1,
				'post_parent' => $intParentPostId
			);	
			
			try{
				//add ticket reply
				$intArticleId = Posts::getInstance()->insert($args);	
				
				//upload attachments
				if($_FILES['attach']['error'] == UPLOAD_ERR_OK){						
					$path = $this->uploadAttachment($_FILES['attach']);
					$attachField = Posts::getInstance()->getFieldByName('helpdesk-attachment');
					Posts::getInstance()->updateField($intArticleId, $attachField['field_id'], $path);
				}			
				
				//get parent ticket info
				$parentPost = Posts::getInstance()->get($intParentPostId);
				
				//write log
				Logs::getInstance()->insert(array(
					'user_id' => Yii::app()->user->id,
					'user_ip' => Utils::getIp(),
					'user_agent' => $_SERVER['HTTP_USER_AGENT'],
					'log_action' => 'HELPDESK_REPLY_TICKET',
					'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b>'.' reply ticket '.'<a href="/tickets/'.$parentPost['post_parent'].'.html">'.$parentPost['post_title'].'</a>'
				));
				
				//send mail
				$args = array(
					'creator_id' => Yii::app()->user->id,
					'ticket_creator_id' => $parentPost['post_creator_id'],
					'ticket_id' => $intParentPostId,
					'ticket_title' => $parentPost['post_title'],
					'ticket_body' => Yii::app()->request->getParam('body', null),
					'category_id' => isset($parentPost['post_category_id'])?$parentPost['post_category_id']:array()
				);
				HelpDesk::getInstance()->sendMail('ticket', $args);
				
				//done
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}
		$this->redirect(array('tickets/detail','postId'=>$intParentPostId));
		exit;
	}
	
	public function actionChangeStatus(){
		//get params
		$intPostId =  Yii::app()->request->getParam('postId', null);
		$intPostStatus =  Yii::app()->request->getParam('postStatus', null);
		if(Yii::app()->request->isPostRequest)
		{
			try{
				//load detail
				$post = Posts::getInstance()->get($intPostId);
				
				//prevent fake
				if(!empty($post) && $post['taxonomy_id'] == 4){	
					Posts::getInstance()->updateStatus($intPostId, $intPostStatus);
					Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
				}
				else{
					Yii::app()->user->setFlash('error', 'Invalid data');
				}
				
				////get ticket info
				$post = Posts::getInstance()->get($intPostId);
				
				//write log
				$log_action = ($intPostStatus==0) ? 'HELPDESK_CLOSE_TICKET' : 'HELPDESK_OPEN_TICKET';
				$log_message = ($intPostStatus==0)? ' close ticket ' : ' open ticket '; 
				Logs::getInstance()->insert(array(
					'user_id' => Yii::app()->user->id,
					'user_ip' => Utils::getIp(),
					'user_agent' => $_SERVER['HTTP_USER_AGENT'],
					'log_action' => $log_action,
					'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b>'.$log_message. '<a href="/tickets/'.$post['post_id'].'.html">'.$post['post_title'].'</a>'
				));
				
				$this->redirect(array('tickets/detail','postId'=>$intPostId));
			}
			catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}
		$this->redirect('/tickets.html');
	}
	
	public function actionForward(){
		//get params
		$intPostId =  Yii::app()->request->getParam('postId', null);
		$intUserId = Yii::app()->user->id;
		
		/*check if ticket exits + is active + prevent faked id*/
		$post = Posts::getInstance()->get($intPostId);
		if(empty($post) || $post['post_status'] != 1 || $post['taxonomy_id'] != 4){
			$this->redirect('/error.html');
		}

		/*chỉ có creator hoặc nhân viên mới được forward*/
		if($post['post_creator_id'] != $intUserId && !Yii::app()->user->isStaff()){
			$this->redirect('/error.html');
		}
		
		/*load list of depts*/
		$arrDepts = HelpDesk::getInstance()->getDepts(true); //o($arrDepts);
		
		if(Yii::app()->request->isPostRequest)
		{
			try{
				//udpate category (dept & subject)
				$arrCategoryIds =   Yii::app()->request->getParam('dept', null);
				if(!empty($arrCategoryIds)){
					Posts::getInstance()->updateCategory($intPostId, $arrCategoryIds);
					
					/*write log*/
					$arrOldTicketCates = HelpDesk::getInstance()->analyseTicketCategory($post['post_category_id'], $arrDepts);
					$arrNewTicketCates = HelpDesk::getInstance()->analyseTicketCategory($arrCategoryIds, $arrDepts);

					$strOldTicketCates = '';
					foreach($arrOldTicketCates as $type => $cate){
						$strOldTicketCates .= $cate['category_name'].' &raquo; ';
					}
					$strOldTicketCates = rtrim($strOldTicketCates, ' &raquo; ');
					
					$strNewTicketCates = '';
					foreach($arrNewTicketCates as $type => $cate){
						$strNewTicketCates .= $cate['category_name'].' &raquo; ';
					}
					$strNewTicketCates = rtrim($strNewTicketCates, ' &raquo; ');
					
					$message = '<b>'.Yii::app()->user->getState('fullname').'</b>'.' forwarded ticket '.'<a href="/tickets/'.$intPostId.'.html">'.$post['post_title'].'</a> from \n"'.$strOldTicketCates.'" \n to \n "'.$strNewTicketCates.'"';
					
					Logs::getInstance()->insert(array(
						'user_id' => Yii::app()->user->id,
						'user_ip' => Utils::getIp(),
						'user_agent' => $_SERVER['HTTP_USER_AGENT'],
						'log_action' => 'HELPDESK_FORWARD_TICKET',
						'log_message' => $message
					));
					
					//send mail 
					$mailInfo = array(
						'forwarder' => Yii::app()->user->id,
						'ticket_creator_id' => $post['post_creator_id'],
						'ticket_id' => $intPostId,
						'ticket_title' => $post['post_title'],
						'old_categories' => $post['post_category_id'],
						'new_categories' => $arrCategoryIds,
						'message' => $message
					);
					HelpDesk::getInstance()->sendMail('forward-ticket', $mailInfo);	
					
					$this->redirect(array('tickets/detail','postId'=>$intPostId));
				}
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}		
		//render layout
		$this->render('forward', array(
			'post' => $post,
			'arrDepts' => $arrDepts
		));
	}
	
	public function actionRate(){
		//get params
		$intPostId =  Yii::app()->request->getParam('postId', null);
		$intUserId = Yii::app()->user->id;
		$intScore =  Yii::app()->request->getParam('score', null);
		if(Yii::app()->request->isPostRequest)
		{
			try{
				//check if data is valid?
				$post = Posts::getInstance()->get($intPostId);
				if(empty($post)) {
					throw new Exception('Can\'t rate because reply does not exist');
				}
				
				$parentPost = Posts::getInstance()->get($post['post_parent']);
				if(empty($parentPost)) {
					throw new Exception('Can\'t rate because ticket does not exist');
				}
				
				//rate reply
				$result = Sentiments::getInstance()->ratePost($intPostId, $intUserId, $intScore);
				
				//send mail
				if($result){
					HelpDesk::getInstance()->sendMail('rate', array(
						'ticket_id' => $post['post_parent'],
						'reply_id' => $intPostId,
						'rated_by' => $intUserId, //ticket creator
						'score' => $intScore,
						'ticketInfo' => $parentPost	,
						'replyInfo' => 	$post	
					));
				}
				
				//write log
				Logs::getInstance()->insert(array(
					'user_id' => Yii::app()->user->id,
					'user_ip' => Utils::getIp(),
					'user_agent' => $_SERVER['HTTP_USER_AGENT'],
					'log_action' => 'HELPDESK_RATE_REPLY',
					'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b> '.
									Yii::t('helpdesk','rated').' '.
									Yii::t('helpdesk',HelpDesk::$_arrTicketRate[$intScore]).
									" (".Yii::t('helpdesk', 'score: {n}/5', intval($intScore)).") ".Yii::t('helpdesk', 'for a rely of').' <a href="/tickets/'.$parentPost['post_id'].'.html">'.$parentPost['post_title'].'</a>'
				));
				echo $result;
				exit;
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}
		$this->redirect('/tickets.html');
	}
	
	private function uploadAttachment($file){
		try{
			/*start uploading...*/
			$objFileTransfer = new FileTransfer(UPLOADS_DIR, array('prefixPath'=>'src/'.date('Y').'/'.date('md')));
			$arrFileInfo = $objFileTransfer->upload($file, 0755, false);
			if($arrFileInfo !== false){
				/*prepare data for inserting db*/
				$args = array(
					'media_title' => $arrFileInfo['filename'],
					'media_file' => $arrFileInfo['path'],
					'media_file_size' => $arrFileInfo['size'],
					'media_file_extension' => $arrFileInfo['extension'],
					'media_src' => 1,
					'media_folder' => 'helpdesk-ticket',
					'media_creator_id' => Yii::app()->user->id
				);
				/*insert into database*/				
				Media::getInstance()->insert($args);
			}
			return isset($arrFileInfo['path'])?$arrFileInfo['path']:null;
		} catch(Exception $ex){
			Yii::app()->user->setFlash('error', $ex->getMessage());
		}
	}
}